package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CarUsed;
import com.isunland.managesystem.entity.CarUsedParams;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.SimpleTreeListParams;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.ZTreeNode;
import com.isunland.managesystem.entity.ZTreeNodeListOriginal;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/6/6 15:37
 */
public class CarUseApplyFragment extends BaseFragment {
  protected static final String EXTRA_CONTENT =
      CarUseApplyActivity.class.getSimpleName() + "EXTRA_CONTENT";
  @BindView(R.id.tv_carUsedData) TextView tvCarUsedData;
  @BindView(R.id.et_carDriver) EditText etCarDriver;
  @BindView(R.id.ib_carDriver) ImageView ibCarDriver;
  @BindView(R.id.et_startStopPlace) EditText etStartStopPlace;
  @BindView(R.id.et_carNum) EditText etCarNum;
  @BindView(R.id.et_carUsedReson) EditText etCarUsedReson;
  @BindView(R.id.tv_dataStatus) TextView tvDataStatus;
  @BindView(R.id.tv_regStaffName) TextView tvRegStaffName;
  @BindView(R.id.tv_regDate) TextView tvRegDate;
  @BindView(R.id.ib_carNum) ImageView ibCarNum;

  private int menuType;
  private static final int REQUEST_DELETE = 6;
  private static final int REQUEST_SUBMIT = 7;
  private static final int ENDREG_SOURCE = 8;
  private final int REQUEST_DATA = 0;
  private final int REQUEST_PERSON = 1;
  private final int ADD = 2;
  private final int NEW = 3;
  private final int SUB = 4;
  private final int PUBLISH = 5;
  private String mId;
  private String driverId;
  private CarUsed mContent;
  private String licensePlateId;
  private boolean carDriverSelect;
  private boolean carNumSelect;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(R.string.carUseApply);
    mContent = (CarUsed) getArguments().get(EXTRA_CONTENT);
    carDriverSelect = false;
    carNumSelect = false;
    if (mContent == null) {
      //添加: 保存,保存并提交
      menuType = ADD;
      mId = UUID.randomUUID().toString();
      driverId = mCurrentUser.getJobNumber();
    }
    if (mContent != null) {
      mId = mContent.getId();
      driverId = mContent.getDriverId();
      //详情
      if (DataStatus.NEW.equalsIgnoreCase(mContent.getDataStatus())) {
        //草稿:保存,提交,删除
        menuType = NEW;
      } else if (DataStatus.WAIT_CHECK.equalsIgnoreCase(mContent.getDataStatus())) {
        //提交: 终止流程
        menuType = SUB;
      } else if (DataStatus.ABORT.equalsIgnoreCase(mContent.getDataStatus())) {
        //终止: 保存,提交,删除
        menuType = NEW;
      } else if (DataStatus.CHECK_PASS.equalsIgnoreCase(mContent.getDataStatus())) {
        //已审核: 车辆使用登记
        menuType = PUBLISH;
      }
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    switch (menuType) {
      //草稿状态：保存、保存并提交
      case ADD:
        inflater.inflate(R.menu.menu_save_submit, menu);
        menu.getItem(1).setTitle(R.string.submit);
        break;
      //草稿状态：保存、提交、删除
      case NEW:
        inflater.inflate(R.menu.menu_save_submit_delete, menu);
        menu.getItem(1).setTitle(R.string.submit);
        break;
      //提交状态：返回修改
      case SUB:
        inflater.inflate(R.menu.menu_stop, menu);
        break;
      //审核通过： 车辆使用,返回修改
      case PUBLISH:
        inflater.inflate(R.menu.menu_regist_stop, menu);
        break;
      default:
        break;
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();

        return true;
      case R.id.menu_item_save:
        //保存
        if (isCorrectInput()) {
          String SAVE = "save";
          volleyPostSave(SAVE);
        }
        return true;
      case R.id.menu_item_submit:
        //保存并提交
        boolean isCorrectSubmit = isCorrectInput();
        if (isCorrectSubmit) {
          showDialog(BaseConfirmDialogFragment.newInstance(R.string.start_up_hint), REQUEST_SUBMIT);
        }
        return true;
      case R.id.menu_item_delete:
        //删除
        showDialog(BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm), REQUEST_DELETE);
        return true;
      case R.id.menu_item_stop:
        // 返回修改
        volleyPostAbort();
        return true;
      case R.id.menu_item_regist:
        // 车辆使用
        CarUsedParams carUsedParams = new CarUsedParams();
        carUsedParams.setMainId(mId);
        carUsedParams.setMainNames("");
        carUsedParams.setFrom(CarUsedParams.CAR_APPLY);
        CarUsedListActivity.newInstance(this, mActivity, 0, carUsedParams, mContent);
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_car_used_apply, container, false);
    ButterKnife.bind(this, view);
    return view;
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    if (mContent != null) {
      tvCarUsedData.setText(mContent.getUseDate());
      etCarDriver.setText(mContent.getDriverName());
      etCarNum.setText(mContent.getLicensePlateNumber());
      etStartStopPlace.setText(mContent.getStartStopPlace());
      etCarUsedReson.setText(mContent.getCauseRoute());
      MyUtils.switchDataStutus(getActivity(), tvDataStatus, mContent.getDataStatus());
      tvRegStaffName.setText(mContent.getRegStaffName());
      tvRegDate.setText(mContent.getRegDate());
    } else {
      tvCarUsedData.setText(MyDateUtil.format(new Date(),MyDateUtil.TYPE_ALL));
      etCarDriver.setText(mCurrentUser.getRealName());
      MyUtils.switchDataStutus(getActivity(), tvDataStatus, DataStatus.NEW);
      tvRegStaffName.setText(mCurrentUser.getRealName());
      tvRegDate.setText(MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE));
    }
    if (menuType == SUB || menuType == PUBLISH) {
      tvCarUsedData.setEnabled(false);
      etCarDriver.setEnabled(false);
      ibCarDriver.setEnabled(false);
      etStartStopPlace.setEnabled(false);
      etCarNum.setEnabled(false);
      ibCarNum.setEnabled(false);
      etCarUsedReson.setEnabled(false);
    }
    //驾驶员
    etCarDriver.addTextChangedListener(textWatcher(CARDRIVER));
    //车辆资源
    etCarNum.addTextChangedListener(textWatcher(CARSOURCE));
  }

  @OnClick({ R.id.tv_carUsedData, R.id.ib_carDriver, R.id.ib_carNum })
  public void onClick(View view) {
    switch (view.getId()) {
      case R.id.tv_carUsedData:
        showDialog(BaseTimeDialogFragment.newInstance(
            mContent == null ? new Date() : MyDateUtil.parse(tvCarUsedData.getText().toString())),
            REQUEST_DATA);
        break;
      case R.id.ib_carDriver:
        Intent driver = new Intent(getActivity(), SearchPersonActivity.class);
        driver.putExtra(SearchPersonListFragment.EXTRA_FROM, SearchPersonListFragment.VALUE_COMMON);
        startActivityForResult(driver, REQUEST_PERSON);
        break;
      case R.id.ib_carNum:
        //资源
        volleyGetSource();
        break;
      default:
        break;
    }
  }

  /** 测试项目类别 */
  private void volleyGetSource() {
    SimpleTreeListParams params = new SimpleTreeListParams();
    ZTreeNode item = new ZTreeNode();
    item.setName("资源目录");
    item.setId("0");
    params.setItem(item);
    params.setChildField("id");
    params.setParentField("pid");
    params.setTitleField("name");
    params.setTitle("请选择资源目录");
    params.setClassOriginal(ZTreeNodeListOriginal.class);
    params.setUrl(ApiConst.URL_CAR_APPLY_SOURCE);
    params.setSelectType(SimpleTreeListParams.ONLY_CHILD);//只能选择最底层节点
    params.setParamsNotEmpty(
        new ParamsNotEmpty().put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode())
            .put("dictFlg", "resouceKindCode")
            .put("dataStatus", "publish"));
    BaseVolleyActivity.newInstance(this, ZTreeListActivity.class, params, ENDREG_SOURCE);
  }

  private void volleyPostAbort() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_CAR_USED_APPLY_BACK);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    params.put("dataStatus", DataStatus.ABORT);
    params.put("runId", mContent.getRunId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  private void volleyPostSave(String type) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_CAR_USED_APPLY_SAVE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    params.put("licensePlateId", licensePlateId);//车辆资源id
    params.put("licensePlateNumber", etCarNum.getText().toString());//车牌号
    params.put("useDate", tvCarUsedData.getText().toString());
    params.put("driverId", driverId);
    params.put("driverName", etCarDriver.getText().toString());
    params.put("startStopPlace", etStartStopPlace.getText().toString());
    params.put("causeRoute", etCarUsedReson.getText().toString());
    params.put("saveOrRun", type);
    if (mContent != null) {
      params.put("dataStatus", mContent.getDataStatus());
    } else {
      params.put("dataStatus", "");
    }
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  //删除
  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_CAR_USED_APPLY_DEL);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getResponse());
  }

  public VolleyResponse getResponse() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage message = new Gson().fromJson(arg0, SuccessMessage.class);
        if (message.getResult() == null) {
          ToastUtil.show(R.string.failure_operation);
          return;
        }
        if (message.getResult() != null && SuccessMessage.SUCCESS.equalsIgnoreCase(
            message.getResult())) {
          ToastUtil.show(R.string.success_operation);
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
        if (message.getResult() != null && SuccessMessage.FAILURE.equalsIgnoreCase(
            message.getResult())) {
          ToastUtil.show(message.getMessage());
        }
      }
    };
  }

  private boolean isCorrectInput() {
    if (TextUtils.isEmpty(tvCarUsedData.getText().toString()) || TextUtils.isEmpty(
        etCarDriver.getText().toString()) || TextUtils.isEmpty(
        etStartStopPlace.getText().toString()) || TextUtils.isEmpty(
        etCarNum.getText().toString())) {
      ToastUtil.show(R.string.notComplete);
      return false;
    } else {
      return true;
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }

    if (requestCode == REQUEST_DATA) {
      Date acquireDate = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
      String usedDate = MyDateUtil.dateToString(acquireDate, MyDateUtil.TYPE_ALL);
      tvCarUsedData.setText(usedDate);
    }
    if (requestCode == REQUEST_PERSON) {
      CustomerDialog dialog =
          (CustomerDialog) data.getSerializableExtra(SearchPersonListFragment.EXTRA_VALUE);
      driverId = dialog.getJobNo();
      carDriverSelect = true;
      etCarDriver.setText(dialog.getName());
    }
    if (requestCode == ENDREG_SOURCE) {
      //资源目录
      SimpleTreeListParams params = (SimpleTreeListParams) data.getSerializableExtra(EXTRA_PARAMS);
      ZTreeNode item = ((ZTreeNode) params.getItem());
      licensePlateId = item.getId();
      carNumSelect = true;
      etCarNum.setText(item.getName());
    }
    if (requestCode == REQUEST_DELETE) {
      volleyPostDelete();
    }
    if (requestCode == REQUEST_SUBMIT) {
      String RUN = "run";
      volleyPostSave(RUN);
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  final int CARDRIVER = 1;
  final int CARSOURCE = 2;

  protected TextWatcher textWatcher(final int type) {
    return new TextWatcher() {
      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
        switch (type) {
          case CARDRIVER:
            //如果是选择不监听文字变化
            if (!carDriverSelect) {
              driverId = "";
              carDriverSelect = false;
            }
            break;
          case CARSOURCE:
            if (!carNumSelect) {
              licensePlateId = "";
              carNumSelect = false;
            }
            break;
          default:
        }
      }

      @Override public void afterTextChanged(Editable s) {

      }
    };
  }

  public static CarUseApplyFragment newInstance(CarUsed content) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, content);
    CarUseApplyFragment fragment = new CarUseApplyFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
